/**
 * Program   :   UpdateServiceImpl.java
 * Author    :   shadow guo
 * Create    :   2013-7-6 下午9:14:42
 *
 * Copyright 2008 by Tongfu Information Technology Co. Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Tongfu Information Technology Co. Ltd. ("Confidential Information").  You
 * shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with Tongfu Information Technology Co. Ltd.
 * 
 */
package com.tongfusoft.web.core.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.tongfusoft.da.DataAccessSession;
import com.tongfusoft.da.DataAccessSessionFactory;
import com.tongfusoft.da.help.DBUtils;
import com.tongfusoft.exception.ServiceException;
import com.tongfusoft.web.core.data.BaseData;
import com.tongfusoft.web.core.service.IUpdateService;

public class UpdateServiceImpl implements IUpdateService<BaseData>{

	@Override
	public boolean update(BaseData obj, Map params) {
		if(DBUtils.executeUpdateDynamic(genSQL(obj,params,obj.getFieldMap()), params) == 1){
			return true;
		}else{
			return false;	
		}
		
	}

	@Override
	public boolean update(BaseData obj, List<Map> params) {
		List<String> sqls = new ArrayList<String>(params.size());
		Map<String,String> fields = obj.getFieldMap();
		
		for(int i=0;i<params.size();i++){
			sqls.add(genSQL(obj,params.get(i),fields));
		}
		
		DataAccessSession session = null;
		try{
			session = DataAccessSessionFactory.openSession(false);
			for(int i=0;i<sqls.size();i++){
				DBUtils.executeUpdateDynamic(sqls.get(i), params.get(i));
			}
			session.commit();
			return true;
		} catch (Exception e){
			session.rollback();
			throw new ServiceException(e);
		} finally {
			session.close();
		}
	}
	
	private String genSQL(BaseData obj, Map params,Map<String,String> fields){
		StringBuffer sb = new StringBuffer();
		sb.append("update ").append(obj.getTableName()).append(" set ");
		
		Iterator<Entry<String,String>> iter = fields.entrySet().iterator();
		while(iter.hasNext()){
			Entry<String,String> entry = iter.next();
			if(!entry.getKey().equals(obj.getPkName())){
				//不是pk
				if(params.containsKey(entry.getKey())){
					sb.append(" ").append(entry.getValue()).append(" = #{").append(entry.getKey()).append("} ,");
				}
			}
		}
		
		sb.deleteCharAt(sb.length()-1);
		sb.append(" where ").append(fields.get(obj.getPkName())).append(" = #{").append(obj.getPkName()).append("} ");
		
		return sb.toString();
	}

}
